module(..., package.seeall)

local imgPath = "images/"
local myImages = {
	"jessica_100.jpg",
	"andy_100.jpg",
	"aya_100.jpg",
	"jessica_100.jpg",
	"jessica_100.jpg",
	"jessica_100.jpg",
	"jessica_100.jpg"
}
local index = 1


--====================================================================--
-- SCENE: LAB
--====================================================================--

new = function ( params )
	
	------------------
	-- Params
	------------------
	
	local vLabel = "- LAB -"
	local vReload = false
	local start_grid = 1
	--
	if type( params ) == "table" then
		--
		if type( params.label ) == "string" then
			vLabel = params.label
		end
		--
		if type( params.reload ) == "boolean" then
			vReload = params.reload
		end
		--
		if type( params.start_grid ) == "integer" then
			start_grid = params.start_grid
		else
			start_grid = 1
		end
		--
	end
	
	------------------
	-- Groups
	------------------
	
	local localGroup = display.newGroup()
	
	local dragGroup = display.newGroup();

	------------------
	-- Display Objects
	------------------
	
	local background = display.newImage( "background2.png" )
	local title = display.newText( vLabel, 0, 0, native.systemFontBold, 16 )
	
	offSetX = 160
	-- local qq = display.newImage( imgPath .. "jessica_600x900.jpg" )
	-- qq.x = 0 + offSetX
	-- qq.y = 0
	-- qq.width = 200
	-- qq.height = 300
	-- local qq2 = display.newImage( imgPath .. "ironman_200x300.jpg" )
	-- qq2.x = 100 + 2*offSetX
	-- qq2.y = 0
	-- local qq3 = display.newImage( imgPath .. "padukon_200x300.jpg" )
	-- qq3.x = 160 + 3*offSetX
	-- qq3.y = 0
	-- local qq4 = display.newImage( imgPath .. "hulk_200x300.jpg" )
	-- qq4.x = 260*3
	-- qq4.y = 0
	-- local qq5 = display.newImage( imgPath .. "hulk_200x300.jpg" )
	-- qq5.x = 260*4
	-- qq5.y = 0

	-- dragGroup:insert(qq)
	-- dragGroup:insert(qq2)
	-- dragGroup:insert(qq3)
	-- dragGroup:insert(qq4)
	-- dragGroup:insert(qq5)
	dragGroup.x = 0;
	dragGroup.y = 230;
	
	--grid
	itemWidth = 200
	itemHeight = 300
	unit_w = 200
	unit_h = 300
	gridGroup = display.newGroup()
	gridGroup.y = -150
	function makeTiles(rowcnt,colcnt,unit_w,unit_h,cellpadding,leftmargin,topmargin)
		
		for i = 1, rowcnt, 1 do
			for j = 1, colcnt, 1 do
				x = (j-1)*(unit_w + cellpadding)+leftmargin
				y = topmargin + (i-1)*(unit_h + cellpadding)
				local unit = display.newRect( x, y, unit_w, unit_h )
				unit.alpha = 0.5
				gridGroup:insert(unit)

			end
		end
	end
	function putGrid(row,column,img,grid,cellpadding,leftmargin,topmargin)
		local  item = display.newImageRect( img, itemWidth, itemHeight )
		item.x = (column-1)*(unit_w + cellpadding) + offSetX
		item.y = 150
		grid:insert(item)
	end
	function putGridZero(row,column,img,grid,cellpadding,leftmargin,topmargin)
		local  item = display.newImageRect( img, itemWidth, itemHeight )
		item.x = (column-1)*(unit_w + cellpadding) + offSetX
		item.y = 150
		item.alpha = 0.5
		grid:insert(item)
	end
	function scrollGrid(i)
		i = i-1
		--dragGroup.x = -(i*(260))  -- i*(itemWidth + cellpadding)
		tween = transition.to( dragGroup, {time=400, x=-(i*(260)) } )
		--tween = transition.to( dragGroup, {time=400, x=-(i*(260)), transition=easing.outExpo } )
		--tween = transition.to( items[itemNum+1], {time=400, x=screenW*.5, transition=easing.outExpo } )
	end
	function calcIndex(dist)
		-- 0, 320, 
		print (dist)
	end
	
	makeTiles(1,5,200,300,60,60,0)
	putGrid(1,1,imgPath .. "therockk_200x300.jpg",gridGroup,60,60,5)
	putGrid(1,2,imgPath .. "hulk_200x300.jpg",gridGroup,60,60,5)
	putGridZero(1,2,imgPath .. "goku_200x300.jpg",gridGroup,60,60,5)
	--putGrid(1,3,imgPath .. "afro_samurai.png",gridGroup,60,60,5)
	--putGrid(1,3,imgPath .. "padukon_200x300.jpg",gridGroup,60,60,5)
	putGrid(1,4,imgPath .. "ironman_200x300.jpg",gridGroup,60,60,5)
	--putGrid(1,5,imgPath .. "jessica_200x300.jpg",gridGroup,60,60,5)
	putGrid(1,6,imgPath .. "chopra_200x300.jpg",gridGroup,60,60,5)
	
		for i=1,5,1 do
			maxrow=1
			maxcol=5
			r = math.ceil(i/maxrow) --what row?
			c = i - (r-1)*maxcol    --what column?
			--putGrid(r,c,myImages[i],gridGroup,60,60,5)
			print("row=",r ,"col=", c)
		end
	dragGroup:insert(gridGroup)
	
	--back button
	local backbt_touched = function ( event )
		--background:removeEventListener( "touch" , touched )
		print("touched jessica")
		director:changeScene( "field", "moveFromLeft" )
		return true
	end
	local backbt = display.newImage(imgPath .. "arrow_left_48.png");
	backbt:addEventListener( "touch" , backbt_touched )
	backbt.x = 30
	backbt.y = 200	

	--go tower button
	local gotowerbt_touched = function ( event )
		--background:removeEventListener( "touch" , touched )
		print("touched gotower button")
		director:changeScene( "tower", "overFromRight" )
		return true
	end
	local gotowerbt = display.newImage(imgPath .. "arrow_right_48.png");
	gotowerbt:addEventListener( "touch" , gotowerbt_touched )
	gotowerbt.x = 290
	gotowerbt.y = 200

	local widget = require "widget"
	--summon button
	local function onSummonEvent( event )
		local btn = event.target
		if event.phase == "press" then
			print( "User has began pressing the button with id: " .. btn.id )
		elseif event.phase == "moved" then
			print( "User has dragged their finger while pressing the button." )
		elseif event.phase == "release" then
			print( "User has lifted finger from button." )        
		end
		return true;
	end
	local summonBtn = widget.newButton{
		id = "summonBtn",
		default =  imgPath .. "summon_32.png",
		over =  imgPath .. "ball_32.png",
		width = 32, height = 32,
		onEvent = onSummonEvent
	}
	summonBtn.x = 280
	summonBtn.y = 280

	--gacha button
	local function onGachaEvent( event )
		local btn = event.target
		if event.phase == "press" then
			print( "User has began pressing the button with id: " .. btn.id )
		elseif event.phase == "moved" then
			print( "User has dragged their finger while pressing the button." )
		elseif event.phase == "release" then
			print( "User has lifted finger from button." )        
		end
		return true;
	end
	local gachaBtn = widget.newButton{
		id = "gachaBtn",
		default =  imgPath .. "gacha_32.png",
		over =  imgPath .. "ball_32.png",
		width = 32, height = 32,
		onEvent = onGachaEvent
	}
	gachaBtn.x = 280
	gachaBtn.y = 320

	--mix button
	local function onMixEvent( event )
		local btn = event.target
		if event.phase == "press" then
			print( "User has began pressing the button with id: " .. btn.id )
		elseif event.phase == "moved" then
			print( "User has dragged their finger while pressing the button." )
		elseif event.phase == "release" then
			print( "User has lifted finger from button." )        
		end
		return true;
	end
	local mixBtn = widget.newButton{
		id = "mixBtn",
		default =  imgPath .. "mix_32.png",
		over =  imgPath .. "ball_32.png",
		width = 32, height = 32,
		onEvent = onMixEvent
	}
	mixBtn.x = 280
	mixBtn.y = 360

	--mission (quest) button
	local function onMissionEvent( event )
		local btn = event.target
		if event.phase == "press" then
			print( "User has began pressing the button with id: " .. btn.id )
		elseif event.phase == "moved" then
			print( "User has dragged their finger while pressing the button." )
		elseif event.phase == "release" then
			print( "User has lifted finger from button." )        
		end
		return true;
	end
	local missionBtn = widget.newButton{
		id = "missionBtn",
		default =  imgPath .. "missionButton.png",
		over =  imgPath .. "ball_32.png",
		width = 32, height = 32,
		onEvent = onMissionEvent
	}
	missionBtn.x = 50
	missionBtn.y = 350
	
	--inventory button
	local function onInventoryEvent( event )
		local btn = event.target
		if event.phase == "press" then
			print( "User has began pressing the button with id: " .. btn.id )
			director:changeScene( { back_scene="lab", start_grid=6 }, "inventory", "moveFromTop" )
		elseif event.phase == "moved" then
			print( "User has dragged their finger while pressing the button." )
		elseif event.phase == "release" then
			print( "User has lifted finger from button." )        
		end
		return true;
	end
	local inventoryBtn = widget.newButton{
		id = "inventoryBtn",
		default =  imgPath .. "inventory_72.png",
		over =  imgPath .. "ball_32.png",
		width = 72, height = 72,
		onEvent = onInventoryEvent
	}
	inventoryBtn.x = 160
	inventoryBtn.y = 50

	--deck button
	local function onDeckEvent( event )
		local btn = event.target
		if event.phase == "press" then
			print( "User has began pressing the button with id: " .. btn.id )
		elseif event.phase == "moved" then
			print( "User has dragged their finger while pressing the button." )
		elseif event.phase == "release" then
			print( "User has lifted finger from button." )        
		end
		return true;
	end
	local deckBtn = widget.newButton{
		id = "deckBtn",
		default =  imgPath .. "summon_32.png",
		over =  imgPath .. "ball_32.png",
		width = 32, height = 32,
		onEvent = onDeckEvent
	}
	deckBtn.x = 280
	deckBtn.y = 70
	
	if (1 ~= 1) then
		print("xxxxxxxxxxx=", start_grid)
	end
	scrollGrid(start_grid)

require "sqlite3"
--Open data.db.  If the file doesn't exist it will be created
local path = system.pathForFile("db/montower", system.ResourceDirectory)
db = sqlite3.open( path )  

	--level group
	local function displayLevel()
		 -- level bar
		local myRectangleInner = display.newRect(11, 51, 35, 4)
		myRectangleInner.strokeWidth = 0
		myRectangleInner:setFillColor(255, 255, 0)
		myRectangleInner:setStrokeColor(0, 222, 222)

		local myRectangle = display.newRect(10, 50, 50, 6)
		myRectangle.strokeWidth = 1.5
		myRectangle:setFillColor(255, 0 , 0)
		myRectangle:setStrokeColor(0, 0, 0)

		 -- coin
		local imgCoin = display.newImage( imgPath .. "coin.png" )
		imgCoin.x = 20
		imgCoin.y = 68
		
		local coin_count = 0
		local user_level = 0
		
		--print all the table contents from db
		for row in db:nrows("SELECT * FROM data") do
		  local text = row._id.." "..row.coin_count
		  coin_count = row.coin_count
		  user_level = row.user_level
		  --local t = display.newText(coin_count, 200, 30 * row._id, null, 16)
		  --t:setTextColor(255,0,0)
		end
		 -- coin text
		local txtCoin = display.newText( coin_count, 35, 62, native.systemFontBold, 11 )
		 --level text
		local level   = display.newText( "LV. " .. user_level, 10, 35, native.systemFontBold, 13 )

	end
	
	levelBar.displayLevelBar()
	
	--start sprite
	local baseline = 300
	-- A sprite sheet with a green dude
	--local sheet2 = graphics.newImageSheet( "greenman.png", { width=128, height=128, numFrames=15 } )
	---local sheet2 = graphics.newImageSheet( "finalflyingdragon.png", { width=96, height=96, numFrames=16 } )


	-- play 15 frames every 500 ms
	---local instance2 = display.newSprite( sheet2, { name="man", start=1, count=16, time=3000 } )
	---instance2.x = display.contentWidth/2
	---instance2.y = baseline - 55
	---instance2:play()

	---instance2:addEventListener( "touch", onDeckEvent )
	--end aprite
	
	local qq_monster = display.newImage( imgPath .. "summon_48.png" )
	qq_monster.x = display.contentWidth/2
	qq_monster.y = baseline
	--qqTween = transition.to( qq_monster, {time=400, y=350} )

	 
	local moveUp
	local moveDown
	function moveUp()
			print("moveUp()")
			transition.to( qq_monster, { time=2000, delay=0, y=display.contentHeight/2-50, onComplete=moveDown} )
	end
	 
	function moveDown()
			transition.to( qq_monster, { time=2000, delay=0, y=display.contentHeight/2, onComplete=moveUp} )
	end	
	--transition.to( qq_monster, { time=2000, delay=500, y=display.contentHeight/2+50, onComplete=moveUp} )
	moveUp()


	

	-- local button = widget.newButton{
		-- label = "The Button",
		-- font = "HelveticaNeue-Bold",
		-- default =  imgPath .. "btn_bg.png",
		-- fontSize = 16
	-- }
	-- button.x = display.contentCenterX
	-- button.y = display.contentCenterY

	
	--====================================================================--
	-- BUTTONS
	--====================================================================--
	
	------------------
	-- Functions
	------------------
	
	local bt01t = function ( event )
		if event.phase == "release" then
			director:changeScene( "field", "moveFromLeft" )
			return true
		end
	end
	--
	local bt02t = function ( event )
		if event.phase == "release" then
			director:changeScene( "tower", "overFromRight" )
			return true
		end
	end
	
	------------------
	-- UI Objects
	------------------
		
	
	
	------------------
	-- Listeners
	------------------
	
	local touched_old = function ( event )
		if event.phase == "ended" then
			if vReload then
				director:changeScene( { label="Scene Reloaded" }, "screen2","moveFromRight" )
			else
				director:changeScene( "screen1", "crossfade" )
			end
		end
	end
	local touched = function ( event )
		if ( event.phase == "began" ) then
			print("slides", event.phase)
            -- Subsequent touch events will target button even if they are outside the contentBounds of button
			startPos = event.x
			prevPos = event.x
			
		elseif event.phase == "ended" then
			print("bg dragged")
			dragGroup.x = dragGroup.x - 20
		end
	end
	function touchListener (self, touch) 
		local phase = touch.phase
		local startDragX,endDragX
		
		print("slides", phase)
		if ( phase == "began" ) then
            -- Subsequent touch events will target button even if they are outside the contentBounds of button
            display.getCurrentStage():setFocus( self )
            self.isFocus = true
			startDragX = dragGroup.x
			print("startDragX : " , startDragX)

			startPos = touch.x
			prevPos = touch.x
												
        elseif( self.isFocus ) then
        
			if ( phase == "moved" ) then
							
				local delta = touch.x - prevPos
				prevPos = touch.x
				
				dragGroup.x = dragGroup.x + delta
				

			elseif ( phase == "ended" or phase == "cancelled" ) then
				
				dragDistance = touch.x - startPos
				print("dragDistance: " .. dragDistance)
				endDragX = dragGroup.x
				print("endDragX : " , endDragX)
				
				

				scrollGrid(6)
				
				if (dragDistance < -160) then
					--nextImage()
					print(" more than -160")
					if (index >= 6) then
						index = 6
					else
						print("qq == ", math.round(dragDistance/320))
						if (dragDistance < -(160 + 320)) then
							index = index + math.abs(math.round(dragDistance/320))
						else
							index = index + 1
						end
					end
				elseif (dragDistance > 160) then
					--prevImage()
					print(" more than +160")
					index = index - 1
					--dragGroup.x = dragGroup.x + dragDistance
				else
					--cancelMove()
				end
				--dragGroup.x = -(100*4 + 60 + 160)
				-- local index = math.round(endDragX/300)
				-- index = math.abs(index)
				-- print("index = ",index)
				if (endDragX > -200) then
					 scrollGrid(1)
				elseif (endDragX < -1500) then
					scrollGrid(6)
				else
					scrollGrid(index)
				end

									
				if ( phase == "cancelled" ) then		
					print("moved cancelled")
				end

                -- Allow touch events to be sent normally to the objects they "hit"
                display.getCurrentStage():setFocus( nil )
                self.isFocus = false
														
			end
		end
					
		return true
		
	end
	
	--====================================================================--
	-- INITIALIZE
	--====================================================================--
	
	local initVars = function ()
		
		------------------
		-- Inserts
		------------------
		
		localGroup:insert( background )
		localGroup:insert( dragGroup )
		localGroup:insert( title )
		localGroup:insert( backbt )
		localGroup:insert( gotowerbt )
		

				
		------------------
		-- Positions
		------------------
		
		title.x = 160
		title.y = 5
		
		------------------
		-- Colors
		------------------
		
		title:setTextColor( 255,255,255 )
		
		------------------
		-- Listeners
		------------------
		
		--background:addEventListener( "touch" , touched )
		background.touch = touchListener
		background:addEventListener( "touch", background )
		
	end
	
	------------------
	-- Initiate variables
	------------------
	
	initVars()
	
	------------------
	-- MUST return a display.newGroup()
	------------------
	
	return localGroup
	
end
